﻿using ControlHelper.Attributes;
using Creator;
using Creator.Core;
using Creator.Core.Base;
using Creator.Core.Component;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml.Linq;

namespace DesktopCreator.Controls
{
    /// <summary>
    /// UCDropList.xaml 的交互逻辑
    /// </summary>
    public partial class UCDropList : UserControl
    {
        public UCDropList()
        {
            InitializeComponent();
            tvNames.SelectedItemChanged += ListName_SelectionChanged; 
        }

        public event Action<object> OnCreate;
        private Type type;
        private BaseObject baseObj;
        /// <summary>
        /// 创建或者指向
        /// true:创建/fasle：指向
        /// </summary>
        private bool createOrPointo;
        private List<Behaviour> typeBehaviour; 
    
         
        private void ListName_SelectionChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        { 
            //当选中时选择对应组件  
            if (!(tvNames.SelectedItem is TreeViewItem item) || item.Tag == null) return;

            var name = item.Tag?.ToString();
            if (string.IsNullOrEmpty(name)) return;
            object target = null;
            this.ToggleUIVisable();
            if (createOrPointo)
            {
                //创建
                if (baseObj.Behaviours.Where(a => a.GetType().Name == name).Count() > 0)
                {
                    MessageBox.Show("同一个对象，无法创建相同的组件！");
                }
                else 
                    target = Utility.Reflection.CreateObjectShortName(type, name, baseObj);
            }
            else
            {
                //指向
                if (typeBehaviour == null || typeBehaviour.Count == 0) throw new Exception("致命错误");
                var id = long.Parse(name.Split('_')[1]);
                target = typeBehaviour.Where(a => a.Id == id).First();
            }
            OnCreate?.Invoke(target);
    
        }

        public void CreateTpyeName(Type type,BaseObject baseObj)
        {
            createOrPointo = true;
      
            this.baseObj = baseObj;
            this.type = type;
            if (tvNames.Items.Count > 0) return;
            //listName.Items.Clear();
            var cd = Utility.Reflection.GetClassDataTypes(type); 

            var paths = cd.Select(a => new { Path = TryGetPath(a), a.Name }).ToList();
       
            foreach (var item in paths)
            {
                AddPathToTreeView(tvNames, item.Path, item.Name);
            }  
        }
        /// <summary>
        /// 创建当前所有的组件中对应类型的组件
        /// </summary>
        /// <param name="type"></param>
        public void CreateAllRunTypes(Type type)
        {
            createOrPointo = false;
            this.type = type;
            typeBehaviour = SystemData.ProcessObjects
            .Where(obj => obj.Behaviours != null && obj.Behaviours.Count > 0 && !obj.GetType().IsAbstract )
            .SelectMany(obj => obj.Behaviours).Where(a => a.GetType().Equals(type))
            .ToList();

            foreach (var item in typeBehaviour)
            {
                tvNames.Items.Add(new TreeViewItem()
                {
                    Header = item.BaseObject.Name + "_" + item.Id,
                    Tag = item.BaseObject.Name + "_" + item.Id
                });
            }
        }

        private string TryGetPath(Type type)
        {
            string name = null;
            var cma = type.GetCustomAttribute<ComponentMenuAttribute>();
            if (cma != null)
            {
                name = cma.Path;
            }

            return name ?? type.Name;
        }
        private void AddPathToTreeView(TreeView treeView, string path, string name)
        {
            // 拆分路径
            string[] parts = path.Split('/');

            // 从根节点开始添加子节点
            TreeViewItem currentNode = null;
            foreach (string part in parts)
            {
                //查找相同目录下
                var existNode = treeView.Items.OfType<TreeViewItem>().FirstOrDefault(a => a.Header?.ToString() == part);
                if (treeView.Items.Count > 0 && existNode != null)
                {
                    currentNode = existNode;
                    continue;
                }

                // 如果当前节点为空，则创建根节点
                if (currentNode == null)
                {
                    currentNode = new TreeViewItem();
                    currentNode.Header = part;
                    treeView.Items.Add(currentNode);
                }
                else
                {
                    // 检查当前节点是否已经存在相同的子节点
                    bool nodeExists = false;
                    foreach (TreeViewItem item in currentNode.Items)
                    {
                        if (item.Header as string == part)
                        {
                            currentNode = item;
                            nodeExists = true;
                            break;
                        }
                    }

                    // 如果当前节点不存在相同的子节点，则创建新的子节点
                    if (!nodeExists)
                    {
                        TreeViewItem newNode = new TreeViewItem();
                        newNode.Header = part;
                        currentNode.Items.Add(newNode);
                        currentNode = newNode;
                    }
                }
            }
            currentNode.Tag = name;
        }
    }
}
